<template>
  <div>
    <!-- 文章列表 -->
      <van-pull-refresh v-model="isLoading" @refresh="onRefresh">

        <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      offset="50"
      :immediate-check="false"
      @load="onLoad"
    >
      <article-item
    v-for="(item , index) in articleList" :key="index"

    :obj="item"
    >

    </article-item>
    </van-list>
      </van-pull-refresh>

  </div>
</template>

<script>
import ArticleItem from './components/ArticleItem.vue'
import { articlesListAPI } from '@/api'
import { timeAgo } from '@/utils/date.js'
export default {
  components: {
    ArticleItem
  },
  props: {
    cid: Number
  },
  async created () {
    const res = await articlesListAPI({

      channelId: this.cid
    })
    // console.log(this.cid)
    res.data.data.results.forEach(obj => {
      obj.pubdate = this.timeAgo(obj.pubdate)
    })
    this.articleList = res.data.data.results
    this.getArticleList()
    // console.log(this.articleList)
  },
  data () {
    return {
      articleList: [],
      loading: false,
      finished: false,
      nextTime: null, // 用于加载更多分页
      isLoading: false
    }
  },
  methods: {
    async getArticleList () {
      // 获取文章数据列表
      const res = await articlesListAPI({
        channelId: this.cid,
        timestamp: this.netTime
      })
      console.log(res)
      // 回来的数据进行预处理.把时间转成多久之前
      res.data.data.results.forEach((item) => {
        item.pubdate = this.timeAgo(item.pubdate)
      })

      // 如果没有数据的话
      if (res.data.data.results.length === 0) {
        // 告诉list显示底部没有数据了
        this.finished = true
      } else {
        this.nextTime = res.data.data.pre_timestamp
        this.articleList = [...this.articleList, ...res.data.data.results]
        this.loading = false
      }
    },
    timeAgo,
    onLoad () {
      // this.getArticleList()
      if (this.articleList.length > 0) {
        this.getArticleList()
      }
    },
    // 下拉刷新
    onRefresh () {
      // 清空时间戳
      this.nextTime = null
      // 清空数组
      this.articleList = []
      // 重新接口获取数据
      this.getArticleList()
      this.isLoading = false // 顶部加载状态关闭
    }
  }
}
</script>
